<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChRobotGroupMapper;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRobotGroup;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;

class ChRobotGroupService extends AbstractService
{
    public $mapper;

    public function __construct(ChRobotGroupMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function list(array $params)
    {
        $list = ChRobotGroup::query()
            ->select(['id','name'])
            ->withCount(['robots'=>function ($query)use($params) {
                !empty($params['ht_bind_status']) && $query->where('ht_bind_status',1);
                !empty($params['corp_id']) && $query->where('corp_id',$params['corp_id']);
            }])
            ->where('main_uid', $params['main_uid'])
            ->orderBy('created_at', 'desc')
            ->get()->toArray();

        //获取所有未设置分组的机器人数量
        $robotList = ChRobot::query()
            ->select('id')
            ->withPermission((int)$params['uid'])
            ->withCount('groups')
            ->when(function ($query) use ($params) {
                !empty($params['ht_bind_status']) && $query->where('ht_bind_status',1);
                !empty($params['corp_id']) && $query->where('corp_id',$params['corp_id']);
            })
            ->where('group_id', 0)
            ->get();

        //所有机器人数量
        $allRobotCount =$robotList->count();
        //未设置分组的机器数量
        $noGroupRobot = $robotList->filter(function ($item) {
            return $item['groups_count'] == 0;
        })->count();

        $defaultGroup = [
            [
                'id' => '-1',
                'name' => '全部',
                'robots_count' => $allRobotCount
            ],
            [
                'id' => '0',
                'name' => '未设置分组',
                'robots_count' => $noGroupRobot
            ]
        ];

        return array_merge($defaultGroup,$list);
    }

    /**
     * 删除分组
     * @param mixed $id
     * @return bool
     * @throws \Exception
     */
    #[Transaction]
    public function deleteById(mixed $id): bool
    {
        $model = $this->mapper->model::query()
            ->where('id',$id)
            ->first();

        if($model){
            $model->robots()->detach();
            $model->delete();
        }
        return true;
    }

    /**
     * 移动分组
     * @param array $data
     * @return bool
     */
    public function moveGroup(array $data): bool
    {
        $robotIds = json_decode($data['robot_ids'],true);
        $groupId = $data['group_id'];
        $oldGroupId = $data['old_group_id'];
        $type = $data['type'];

        $robotList = ChRobot::query()
            ->with(['groups'=>function ($query) {
                $query->select(['id']);
            }])
            ->whereIn('id',$robotIds)
            ->get();

        $robotList->each(function ($item) use ($groupId, $type, $oldGroupId) {

            $existingGroupIds = $item->groups->pluck('id')->toArray();
            if(in_array($groupId, $existingGroupIds)){
                $item->groups()->detach($groupId);
            }

            if($type == 0){
                //移动至新分组(原分组移出)
                if($groupId == 0){
                    $item->groups()->detach($oldGroupId);
                }else{
                    if($oldGroupId > 0){
                        $item->groups()->detach($oldGroupId);
                    }
                    $item->groups()->attach($groupId);
                }
            }else{
                //添加至新分组(原分组保留)
                if($groupId == 0){
                    $item->groups()->detach($oldGroupId);
                }else{
                    $item->groups()->attach($groupId);
                }
            }
        });
        return true;
    }
}